package m.base.service;

import m.base.model.LevelInfo;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.common.service.Service;
import m.system.cache.CacheUtil;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.ObjectUtil;
import manage.model.StatusModel;
import manage.util.DictionaryUtil;

import java.sql.SQLException;
import java.util.List;

public class LevelInfoService extends Service {
    /**
     * 获取默认商户级别
     */
    public LevelInfo getDefLevel() throws SQLException, MException {
        List<LevelInfo> ls= ModelQueryList.getModelList(LevelInfo.class,new String[]{"*"},null,
            QueryCondition.and(
                QueryCondition.eq("defLevel",LevelInfo.Yes),
                QueryCondition.eq("status", StatusModel.Status_Enable)
            )
        );
        if(ls.isEmpty()) throw new MException(this.getClass(),"没有默认商户级别");
        return ls.get(0);
    }
    /**
     * 获取注册商户级别
     */
    public LevelInfo getApplyLevel() throws SQLException, MException {
        List<LevelInfo> ls= ModelQueryList.getModelList(LevelInfo.class,new String[]{"*"},null,
                QueryCondition.and(
                        QueryCondition.eq("applyLevel",LevelInfo.Yes),
                        QueryCondition.eq("status", StatusModel.Status_Enable)
                )
        );
        if(ls.isEmpty()) throw new MException(this.getClass(),"没有注册商户级别");
        return ls.get(0);
    }
    public String save(LevelInfo model) throws Exception {
        String msg;
        if(LevelInfo.Yes.equals(model.getDefLevel())){
            LevelInfo m=new LevelInfo();
            m.setDefLevel(LevelInfo.No);
            ModelUpdateUtil.update(m,new String[]{"defLevel"}, QueryCondition.eq(new String[]{"oid","oid"}));
        }
        if(LevelInfo.Yes.equals(model.getApplyLevel())){
            LevelInfo m=new LevelInfo();
            m.setApplyLevel(LevelInfo.No);
            ModelUpdateUtil.update(m,new String[]{"applyLevel"}, QueryCondition.eq(new String[]{"oid","oid"}));
        }
        if(ObjectUtil.notEmptyOid(model)){
            ModelUpdateUtil.updateModel(model);
            msg="修改成功";
        }else{
            model.setOid(GenerateID.generatePrimaryKey());
            ModelUpdateUtil.insertModel(model);
            msg="保存成功";
        }
        DictionaryUtil.clear(LevelInfo.class);
        CacheUtil.clear(LevelInfo.class);
        return msg;
    }
}
